package servlet;

import entity.Product;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 * @date 2024年03月23日 15:06
 */
@WebServlet("*.product")
public class ProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        if ("/findAll.product".equals(path)) {
            findAll(request, response);
        }
        if ("/findById.product".equals(path)) {
            findById(request, response);
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 查询商品列表
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Product> products = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }
            request.setAttribute("products",products);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // ajax请求,展示商品详情
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Product product = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()){
                product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));

                // ajax返回时,返回一个JSON格式的字符串
                // 此处如果我们自己手写,容易出现错误,错误还不好找
                // out.print("{'id':"+product.getId()+",'name':'"+product.getName()+"','price':"+product.getPrice()+"}");
                // 可以使用Apache提供的JSON工具
                // 1.将Java对象转换成JSON对象
                // public static JSONObject fromObject(Object object)
                // 该方法表示将一个Java对象object转换成JSON对象
                JSONObject productJson = JSONObject.fromObject(product);
                // JSONObject对象提供了toString方法将JSON对象转换成JSON格式字符串
                out.print(productJson.toString());

                // 2.将Java对象集合转换成JSON数组
//                List<Product> products = new ArrayList<>();
//                JSONArray jsonArray = JSONArray.fromObject(products);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
